package com.taotao.manage.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.github.abel533.entity.Example.Criteria;
import com.taotao.manage.mapper.ContentCategoryMapper;
import com.taotao.manage.pojo.ContentCategory;
/**
 * 内容分类业务
 * @author DuBo
 *
 */
@Service
public class ContentCategoryService extends BaseService<ContentCategory> {

	@Autowired
	private ContentCategoryMapper contentCategoryMapper;

	/**
	 * 保存内容分类和更新是否为父节点
	 * @param parentId
	 * @param name
	 * @return
	 */
	public ContentCategory addContentCategory(Long parentId, String name) {
		ContentCategory category = new ContentCategory();
		category.setParentId(parentId);
		category.setName(name);
		category.setStatus(1);
		category.setIsParent(false);
		Boolean flag = super.save(category);
		if (flag) {
			ContentCategory contentCategory = new ContentCategory();
			contentCategory.setId(parentId);
			contentCategory.setIsParent(true);
			Integer count = super.countByWhere(contentCategory);
			if (count == 0) {
				  flag = super.updateByPrimaryKey(contentCategory);
			}
		}
		if (flag) {
			return category;
		}
		return null;
	}
	/**
	 * 删除内容分类
	 * 业务：
	 *  删除当前分类 
	 *  删除当前分类所有子类目 
	 *  判断当前分类是否有兄弟节点，如果没有，更新父节点isParent=false
	 *  一次删除多条数据 in
	 * @param id
	 * @param parentId
	 * @return
	 */
	public void deleteContentCategory(Long id, Long parentId) {
		
		ContentCategory category = new ContentCategory();
		category.setParentId(parentId);
		Integer count = super.countByWhere(category);
		if(count == 1){
			// 说明没有兄弟节点
			category.setParentId(null);
			category.setIsParent(false);
			category.setId(parentId);
			super.updateByPrimaryKey(category);
		}
		
		// 判断是否有子节点，如果有删除
		ContentCategory myself = super.queryById(id);
		if (myself.getIsParent()) {
			List<Object> ids = new ArrayList<Object>();
			ids.add(id);
			// 递归获取id
			queryChildrenByParentId(parentId, ids);
			// in删除
			Example example = new Example(ContentCategory.class);
			Criteria criteria = example.createCriteria();
			criteria.andIn("id", ids);
			this.contentCategoryMapper.deleteByExample(example);
		}else{
			// 没有子节点
			super.deleteById(id);
		}
		
	}
	
	/**
	 * 递归删除
	 * @param parentId
	 * @param ids
	 */
	public void queryChildrenByParentId(Long parentId,List<Object> ids){
		ContentCategory category = new ContentCategory();
		category.setParentId(parentId);
		List<ContentCategory> listByWhere = super.queryListByWhere(category);
		for(ContentCategory cc : listByWhere){
			ids.add(cc.getId());
			if (cc.getIsParent()) {
				queryChildrenByParentId(cc.getId(),ids);
			}
		}
	}
	
}
